// pages/expressage/expressage.js
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        imgPath: '',
        items: null,
        sender_name: '',
        sender_phone: '',
        sender_addr: '',
        recipient_name: '',
        recipient_phone: '',
        recipient_addr: '',
        waybill_number: '',
        isLoading: false
    },
    // 1.获取百度大脑接口
    getBaiduToken() {
       let apikey = '2ZnvwGLZWYhOGYKD0ZeXY7Fy'
       let seckey = '7J9e2auZghwnwecJpN1yYh437eIHRtfo'
       let tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apikey}&client_secret=${seckey}`
       let that = this
       wx.request({
         url: tokenUrl,
         method: 'POST',
         dataType:'json',
         header:{
           'content-type': 'application/x-www-form-urlencoded'
         },
         success(res){
           console.log('百度大脑调用成功',res);
           that.setData({
             baiduToken:res.data.access_token
           })
          },fail(res){
           console.log('接口获取失败',res);
         }
       })
    },
    // 2.选择图片进行识别
    selectImage() {
      let that = this
      that.getBaiduToken()
      return new Promise(function (resolve, reject) {
        //   先选择
          wx.chooseMedia({
            count: 1,
            mediaType: ['image','video'],
            sourceType: ['album', 'camera'],
            success(res) {
                console.log('选择图片', res);
                that.setData({
                    imgPath: res.tempFiles[0].tempFilePath
                })
                // 再获取
                wx.getFileSystemManager().readFile({
                    filePath: res.tempFiles[0].tempFilePath,
                    encoding: 'base64',
                    success: resolve,
                    fail: reject
                })
            }
          })
      })
    },
    // 3.将图片通过接口扫描识别
    scanImageInfo(imageData) {
        let that = this
        // 修改2：detectUrl
        const detectUrl = `https://aip.baidubce.com/rest/2.0/ocr/v1/waybill?access_token=${that.data.baiduToken}`
        wx.showToast({
          title: '正在识别',
        })
        return new Promise(function (resolve, reject) {
            wx.request({
              url: detectUrl,
              data: {
                  image: imageData
              },
              method: 'POST',
              dataType: 'json',
              header: {
                  'content-Type': 'application/x-www-form-urlencoded'
              },
              success(res, resolve) {
                  console.log('识别成功',res);
                  if (res.data.words_result != 0) {
                    that.setData({
                        sender_name:res.data.words_result[0].sender_name[0].word,
                        sender_phone:res.data.words_result[0].sender_phone[0].word,
                        sender_addr:res.data.words_result[0].sender_addr[0].word,
                        recipient_name:res.data.words_result[0].recipient_name[0].word,
                        recipient_phone:res.data.words_result[0].recipient_phone[0].word,
                        recipient_addr:res.data.words_result[0].recipient_addr[0].word,
                        waybill_number:res.data.words_result[0].waybill_number[0].word
                    })
                } else {
                    wx.showToast({
                      title: '没有识别到快递',
                    })
                }
              }, fail (res, reject) {
                  console.log('请求失败', res.data);
              }
            })
        })
    },
    // 4.返回识别结果
    queryIp() {
     let that = this
     that.setData({
         items: null
     })
     that.selectImage().then(res => {
         console.log("图片信息", res);
         that.scanImageInfo(res.data)
     })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})